package com.splic.product.service.impl.pay;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.splic.common.core.DeviceContext;
import com.splic.common.enums.OrderStatusEnum;
import com.splic.common.exception.BusinessException;
import com.splic.product.domain.Order;
import com.splic.product.domain.Product;
import com.splic.product.dto.CreateOrderDto;
import com.splic.product.dto.CreateOrderReturnDto;
import com.splic.product.service.OrderService;
import com.splic.product.service.ProductService;
import com.splic.product.service.ThirdPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * ==========================
 * 开发：yuxiangjie
 * 创建时间：2022-03-18 15:32
 * 版本: 1.0
 * 描述：TODO
 * ==========================
 */
@Service
@Slf4j
public class WxpayPayService implements ThirdPayService {

    //@Autowired
    //private WxPayService wxPayService;
    @Autowired
    private ProductService productServiceImpl;

    @Autowired
    private OrderService orderServiceImpl;

    @Override
    public CreateOrderReturnDto createPayOrder(Order order, CreateOrderDto dto) {

        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product == null){
            throw new BusinessException("应用获取失败");
        }

        JSONObject jsonObject = JSONObject.parseObject(product.getWechatConfig());
        if (jsonObject == null){
            throw new BusinessException("应用支付参数获取失败");
        }
        // 微信统一下单请求对象
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setOutTradeNo(order.getOrderNo());
        request.setBody(order.getGoodsName());
        request.setFeeType("CNY");
        BigDecimal amountFee = new BigDecimal(100).multiply(order.getAmount());
        request.setTotalFee(amountFee.intValue());
        request.setSpbillCreateIp(dto.getIp());
        request.setNotifyUrl(jsonObject.getString("notifyUrl"));

        request.setTradeType(WxPayConstants.TradeType.APP);
        request.setSignType(WxPayConstants.SignType.MD5);

        // 调起上游接口：
        // 1. 如果抛异常，则订单状态为： 生成状态，此时没有查单处理操作。 订单将超时关闭
        // 2. 接口调用成功， 后续异常需进行捕捉， 如果 逻辑代码出现异常则需要走完正常流程，此时订单状态为： 支付中， 需要查单处理。
        CreateOrderReturnDto returnDto = new CreateOrderReturnDto();
        try {

            WxPayService wxPayService = getWxPayService(jsonObject);
            WxPayAppOrderResult payResult = wxPayService.createOrder(request);
            BeanUtils.copyProperties(payResult,returnDto);
        } catch (WxPayException e) {
           log.error("创建微信支付订单失败:{}",e);
        }
        return returnDto;
    }

    @Override
    public int checkOrder(Order order) {
        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product != null){
            JSONObject jsonObject = JSONObject.parseObject(product.getWechatConfig());
            if (jsonObject != null){
                try {
                    WxPayService wxPayService = getWxPayService(jsonObject);
                    WxPayOrderQueryResult result = wxPayService.queryOrder(null, order.getOrderNo());
                    System.out.println(result.getXmlString());
                    if ("SUCCESS".equals(result.getReturnCode()) && "SUCCESS".equals(result.getResultCode()) && "SUCCESS".equals(result.getTradeState()) ) {
                        order.setStatus(OrderStatusEnum.PAY_SUCCESS.getCode());
                        orderServiceImpl.updateOrderStatus(order);
                        return 0;
                    }
                } catch (WxPayException e) {
                    log.error("微信查询订单" + order.getOrderNo() + "失败！", e);
                }
            } else {
               log.error("应用支付参数获取失败");
            }
        } else {
            log.error("应用获取失败");
        }
        return -1;
    }


    public WxPayService getWxPayService(JSONObject jsonObject){
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setMchId(jsonObject.getString("mchId"));
        wxPayConfig.setAppId(jsonObject.getString("appId"));
        wxPayConfig.setMchKey(jsonObject.getString("mchKey2"));
        wxPayConfig.setApiV3Key(jsonObject.getString("mchKey3"));
        wxPayConfig.setNotifyUrl(jsonObject.getString("notifyUrl"));
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig); //微信配置信息
        return wxPayService;
    }

    public WxPayService getWxPayService(Long productId){
        Product product = productServiceImpl.selectProductById(productId);
        if (product == null){
            throw new BusinessException("应用获取失败");
        }

        JSONObject jsonObject = JSONObject.parseObject(product.getWechatConfig());
        if (jsonObject == null){
            throw new BusinessException("应用支付参数获取失败");
        }

        return getWxPayService(jsonObject);
    }


}
